from flask import Blueprint, request
from datetime import datetime, timedelta
import utilsapp.common
from utilsapp.mysql_con import db_list, db_table_pagelist, db_insert, db_delete, db_update

project = Blueprint('project', __name__)
tableName = 'project'


# 分页查询
@project.route('/getlist', methods=["post"])
def table_list():
    if 'page' in request.json.keys() and 'size' in request.json.keys():
        page = request.json['page']
        size = request.json['size']
    else:
        page = 1
        size = 999
    j = db_table_pagelist(tableName, page, '', size)
    return j


@project.route('/add', methods=['POST'])
def project_add():
    return db_insert(tableName, request.json)


@project.route('/delete', methods=['POST'])
def sproject_delete():
    id = request.json['id']
    return db_delete(tableName, f'WHERE id=%s', {'id': id})


@project.route('/edit', methods=['POST'])
def project_edit():
    id = request.json['id']
    keys_not_add = ['id']
    addModel = {key: request.json[key]
                for key in request.json if key not in keys_not_add}

    d = db_list(f'SELECT * FROM project where id={id}')['data'][0]

    if len(addModel['template']) > 0:
        addModel['activate_code'] = utilsapp.common.create_code(d['short_name'], int(d['exp_time'].timestamp()), d['win_code'])

    return db_update(tableName, addModel, f'WHERE id=%s', {"id": id})
